package com.xja.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xja.model.entity.Article;
import com.xja.model.vo.resp.Result;
import com.xja.service.IArticleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * @author caijg
 */
@RestController
@RequestMapping("/admin/article")
@Slf4j
@Tag(name = "文章管理")
@RequiredArgsConstructor
public class AdminArticleController {

    private final IArticleService articleService;

    @GetMapping("/list")
    @Operation(summary = "获取文章列表")
    public Result<Page<Article>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer status) {
        log.info("获取文章列表：page = {}, size = {}, title = {}, status = {}",
                page, size, title, status);

        // 构建查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(title)) {
            wrapper.like(Article::getTitle, title);
        }

        if (status != null) {
            wrapper.eq(Article::getStatus, status);
        }
        wrapper.orderByDesc(Article::getCreateTime);

        // 分页查询
        Page<Article> pageResult = articleService.page(
                new Page<>(page, size),
                wrapper
        );

        return Result.success(pageResult);
    }

    @PutMapping("/approve/{id}")
    @Operation(summary = "审核通过文章")
    public Result<Void> approve(@PathVariable Long id) {
        log.info("审核通过文章：id = {}", id);

        boolean success = articleService.update()
                .eq("id", id)
                .set("status", 1)
                .update();

        return success ? Result.success() : Result.error("审核失败");
    }

    @Operation(summary = "删除文章")
    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody ArrayList<String> ids) {
        log.info("删除文章：{}", ids);
        articleService.delete(ids);
        return Result.success();
    }
}